<template>
  <div>
    <form>
      标题<input type="text" v-model="product.title"><br>
      价格<input type="text" v-model="product.price"><br>
      简介<input type="text" v-model="product.intro"><br>
      图片<input type="file" name='img' ref="img" @change="upload"><br>

      <span v-for="(item, index) in product.images" style="position: relative">
          <img :src="item">
          <span @click="removeImg(index)" style="position: absolute; bottom: 0; left: 48%;">X</span>
      </span><br>

      属性<button @click="addParameter" type="button">新增属性</button>

      <div class="paramBox" v-for="(item, index) in product.parameter">
        <input type="text" v-model="item.key">
        <input type="text" v-model="item.value">
        <button type="button" @click="removeParameter(index)">删除</button>
      </div>
      <br>
      <br>
      <br>
      <button type="button" @click="submit">{{isEdit ? '修改' : '添加'}}</button>
    </form>
    <br>
    <br>
    <br>
    <br>
    <!-- <form enctype="multipart/form-data">
      <h1>单图上传</h1>
      <input type="file" name="logo">
      <input type="submit" value="上传">
    </form> -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      product: {
        parameter: [],
        images: []
      },
      isEdit: false
    }
  },
  methods: {
    async submit() {
      if (!this.product.title || !this.product.price || !this.product.intro) {
        alert('不能为空')
        return
      }
      let res = this.isEdit
        ? await this.$store.dispatch('updateProduct', this.product) 
        : await this.$store.dispatch('addProduct', this.product)
      
      
      if (res.success) {
        let msg = this.isEdit ? '修改成功' : '添加成功'
        alert(msg)
        if (this.isEdit) {
          window.location.reload()
        } else {
          this.$router.push('/admin/order')
        }
        
      } 
      

    },
    getUrlParams(name) { 
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i") //定义正则表达式 
      var r = window.location.search.substr(1).match(reg) 
      if (r != null) return unescape(r[2])
      return null
    },
    addParameter() {
      this.product.parameter.push({
        key: '',
        value: ''
      })
    },
    removeParameter(index) {
      this.product.parameter.splice(index, 1)
    },
    async upload() {
      let files = this.$refs.img.files
      let fileData = files[0]
      let data = new FormData()
      data.append('file', fileData)
      let res = await this.$store.dispatch('uplaod', data)
      if (res.success) {
        this.product.images.push(res.data)
      }
      console.log(res)
    },
    removeImg(index) {
      this.product.images.splice(index, 1)
    }
  },
  async beforeMount() {
    let _id = this.getUrlParams('_id')
    if (_id) {
      this.isEdit = true
      let res = await this.$store.dispatch('getProduct', _id)
      if (res.success) this.product = res.data
    }
  }
  
}
</script>

